package com.runen.infinitemovement.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.runen.infinitemovement.R;
import com.runen.infinitemovement.activity.SecondReplyCommentActivity;
import com.runen.infinitemovement.adapter.ContentsAdapter;
import com.runen.infinitemovement.adapter.DiscussionAdapter;
import com.runen.infinitemovement.model.api.ActivityAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.CommentDetailListBean;
import com.runen.infinitemovement.model.entity.MyLongMarchCommentEntity;
import com.runen.infinitemovement.model.entity.ReplyCommentListBean;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ChatFragment extends Fragment {
    @BindView(R.id.rv_discussion_msg)
    RecyclerView rvDiscussionMsg;
    @BindView(R.id.edt_input_text)
    EditText edtInputText;
    @BindView(R.id.ll_input)
    LinearLayout llInput;
    @BindView(R.id.tv_send)
    TextView tvSend;
    private View view;
    private ContentsAdapter contentsAdapter;
    private CommentDetailListBean commentDetailListBean;
    private ReplyCommentListBean replyCommentListBean;
    private String topItemCommentId;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_chat, container, false);
            ButterKnife.bind(this, view);
            iniView();
        }
        return view;
    }

    private void iniView() {
        /**
         * 讨论
         */
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(getActivity());
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        rvDiscussionMsg.setLayoutManager(layoutManager2);
        contentsAdapter = new ContentsAdapter(getActivity());
        rvDiscussionMsg.setAdapter(contentsAdapter);
        initData();
        contentsAdapter.setOnItemCommentClick(new ContentsAdapter.OnItemCommentClick() {
            @Override
            public void onItemPraise(CommentDetailListBean item) {

            }

            @Override
            public void onItemCommentReply(CommentDetailListBean item, String topCommentId) {
                //评论回复
                commentDetailListBean = item;
                topItemCommentId = topCommentId;
                edtInputText.setHint("回复" + item.nickname + "：");
                CommonUtil.showKeyboard(edtInputText);
            }

            @Override
            public void onItemSecondReply(ReplyCommentListBean item, String topCommentId) {
                replyCommentListBean = item;
                topItemCommentId = topCommentId;
                edtInputText.setHint("回复" + item.reviewerName + "：");
                CommonUtil.showKeyboard(edtInputText);
            }

            @Override
            public void onItemMore(CommentDetailListBean item, String topCommentId) {
                Intent intent = new Intent(getActivity(), SecondReplyCommentActivity.class);
                intent.putExtra("commentId", item.commentId);
                intent.putExtra("targetId", item.reviewerId);
                startActivity(intent);
            }
        });

        edtInputText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {//修改回车键功能
                    //代码
                    String edtString = v.getText().toString().trim();
                    if (TextUtils.isEmpty(edtString)) {
                        ToastUtils.showShort("请输入评论信息！！！");
                    } else {
                        onComment(edtString, commentDetailListBean, replyCommentListBean);
                    }
                }
                return false;
            }
        });
        edtInputText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    tvSend.setVisibility(View.VISIBLE);
                } else {
                    tvSend.setVisibility(View.GONE);
                }
            }
        });
        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onComment(edtInputText.getText().toString().trim(), commentDetailListBean, replyCommentListBean);
            }
        });
    }

    /**
     * 对文章的评论
     *
     * @param edtString
     */
    private void onComment(String edtString, final CommentDetailListBean commentDetailList, final ReplyCommentListBean replyCommentList) {
        JSONObject object = new JSONObject();
        try {
            object.put("commentType", "3");
            object.put("content", edtString);
            object.put("replyUserId", UserAPI.getUserId());
            if (null != commentDetailList) {
                object.put("replyId", commentDetailList.commentId);
                object.put("replyUserId", commentDetailList.reviewerId);
                object.put("topCommentId", topItemCommentId);
            } else if (null != replyCommentList) {
                object.put("replyArticleCommentsId", replyCommentList.commentId);
                object.put("replyUserId", replyCommentList.reviewerId);
                object.put("topCommentId", topItemCommentId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().onDynamicComment(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                CommonUtil.hideKeyboard(getActivity());
                edtInputText.setText("");
                edtInputText.setHint("说点什么...");
                tvSend.setVisibility(View.GONE);
                commentDetailListBean = null;
                replyCommentListBean = null;
                initData();
            }
        });
    }

    private void initData() {
        String string = "?commentType=3&limit=100&page=1";
        new ActivityAPI().getMyLongMarchComment(string, new BaseResultCallback<MyLongMarchCommentEntity>() {
            @Override
            public void onResponse(MyLongMarchCommentEntity response) {
                if (response.code == 0) {
                    if (response.data != null && response.data.size() > 0) {
                        contentsAdapter.setNewData(response.data);
                    }
                }
            }
        });
    }
}
